package com.ssm.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ssm.pojo.Manager;
import com.ssm.service.ManagerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class ManagerDataListener extends AnalysisEventListener<Manager> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ManagerDataListener.class);

    private static final int BATCH_COUNT = 5;

    List<Manager> list = new ArrayList<Manager>();
    private ManagerService managerService;

    public ManagerDataListener(ManagerService managerService) {
        this.managerService = managerService;
    }


    public void invoke(Manager manager, AnalysisContext analysisContext) {
        if (manager == null) {
            try {
                throw new Exception("数据为空");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (manager != null) {
            list.add(manager);
        }
        if (list.size() >= BATCH_COUNT) {
            LOGGER.info("{}条数据，开始存储数据库！", list.size());
            System.out.println("==================================================================");
            System.out.println(list);
            int i = managerService.addManagerList(list);
            System.out.println(i);
            LOGGER.info("存储数据库成功！");
            // 存储完成清理 list
            list.clear();
        }

    }

    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        managerService.addManagerList(list);
        LOGGER.info("存储数据库成功！");
        LOGGER.info("所有数据解析完成！");
    }
}
